import axios from 'axios'
import store from '../../store'
import router from '../../router'
import * as code from '../constant/codeConstant'
// import {CODE_RESPONSE_CEDE, CODE_RESPONSECEDE, RESPONSE_SUCCESS} from "core/constant/codeConstant";
// import da from "element-ui/src/locale/lang/da";
// import { MessageBox, Toast, Notify  } from 'vant';
class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {}
    }
    return config
  }
  interceptors (instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
	  // 添加token至请求header中
      if (store.state.user.token) {
        config.headers.Authorization = store.state.user.token
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      const { data, status } = res
      if (status === code.CODE_SUCCESS && data.Code === code.RESPONSE_SUCCESS) {
        return Promise.resolve(data)
      } else {
        if (data.Code === code.CODE_TOKEN_INVALID || (!store.state.token && data.Code === code.CODE_QUEST_INVALID)) {
          // token 无效，清除token / 没传token且 无效请求
          this.resetLogin()
          return Promise.reject(data.Msg)
        } else {
          return Promise.reject(data.Msg)
        }
      }
    }, error => {
      let message = '服务器请求失败'
      // Notify({ type: 'danger', message: message });
      return Promise.reject(error)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }

  /**
   * 重新登录
   */
  resetLogin () {
    store.commit('LOGIN_OUT')
    // Dialog.alert({
    //   title: '提示',
    //   message:'登录失效，请重新登录?',
    // }).then(() => {
    //   router.push({
    //     name: 'login'
    //   })
    // });
  }
}
export default HttpRequest
